package com.cjq.auth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cjq.auth.exception.ServiceException;
import com.cjq.auth.remote.UserRemoteService;
import com.cjq.auth.service.AuthService;
import com.cjq.auth.utils.PasswordUtils;
import com.cjq.common.constants.JwtConstants;
import com.cjq.common.constants.TokenConstants;
import com.cjq.common.domain.User;
import com.cjq.common.domain.request.UserReq;
import com.cjq.common.domain.response.UserRes;
import com.cjq.common.result.Result;
import com.cjq.common.utils.JwtUtils;
import com.cjq.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.cjq.auth.utils.PasswordUtils.check;
import static com.cjq.auth.utils.PasswordUtils.encrypt;

@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private UserRemoteService userRemoteService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;
//    @Autowired
//    private PasswordUtils passwordUtils;
    @Override
    public Result<UserRes> accountLogin(UserReq userReq) {
        if (StringUtils.isBlank(userReq.getUserName())){
            throw new ServiceException("用户名不能为空");
        }
        if (StringUtils.isBlank(userReq.getUserPwd())){
            throw new ServiceException("密码不能为空");
        }
        //远程调用
        Result<User> user = userRemoteService.findUser(userReq.getUserName());
        User data = user.getData();
        if (data==null){
            throw new ServiceException("用户不存在，去注册");
        }
        if (!data.getUserPwd().equals(userReq.getUserPwd())){
            throw new ServiceException("密码错误");
        }
//        // 加盐
//        String salt = UUID.randomUUID().toString().replaceAll("-", "");
//        System.out.println("明文(原生)密码：" + userReq.getUserPwd());
//        // 获取加盐后的MD5值
//        String SaltPassword = encrypt(userReq.getUserPwd(), salt);
//        System.out.println("加盐后的MD密码：" + SaltPassword);
//        String salt1 = SaltPassword.split("\\$")[0];
//        String checkPassword = encrypt(userReq.getUserPwd(),salt1);
//        System.out.println("加盐后的密码和原生密码是否是同一字符串:" + check(userReq.getUserPwd(), checkPassword));
//

        HashMap<String, Object> map = new HashMap<>();
        String userKey = UUID.randomUUID().toString().replaceAll("-", "");
        map.put(JwtConstants.USER_KEY,userKey);
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey, JSONObject.toJSONString(data),15, TimeUnit.MINUTES);
        UserRes userRes = new UserRes();
        userRes.setToken(token);
        userRes.setTime(TokenConstants.TOKEN_EXPIRATION_TIME_STR);
        return Result.success(userRes);
    }

    @Override
    public Result<User> userInfo() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        String userJSONStr = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        return Result.success(JSONObject.parseObject(userJSONStr,User.class));
    }

    @Override
    public Result logout() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        return Result.success(redisTemplate.delete(TokenConstants.LOGIN_TOKEN_KEY + userKey));
    }
}
